package com.cskaoyan.wx.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.wx.bean.vo.GoodsListVo;
import com.cskaoyan.wx.bean.vo.WxGoodsCategoryVo;
import com.cskaoyan.wx.bean.vo.WxGoodsListVo;
import com.cskaoyan.wx.bean.vo.goodsdetail.DetailCommentVo;
import com.cskaoyan.wx.bean.vo.goodsdetail.GoodsSpecificationListVo;
import com.cskaoyan.wx.bean.vo.goodsdetail.WxGoodsDetailVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TreeSet;

@Service
public class WxGoodsServiceImpl implements WxGoodsService {


    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    SearchHistoryMapper searchHistoryMapper;
    Integer id;
    String username;

    @Override
    public WxGoodsCategoryVo currentCategory(Integer id) {

        //先查询当前的Category
        Category currentCategory = categoryMapper.selectByPrimaryKey(id);

        //如果是l1
        if (currentCategory.getLevel().equals("L1")) {

            //查询兄弟Category
            CategoryExample categoryExample = new CategoryExample();
            categoryExample.createCriteria().andPidEqualTo(currentCategory.getId()).andLevelEqualTo("L2");
            List<Category> brotherCategories = categoryMapper.selectByExample(categoryExample);

            Category category = brotherCategories.get(0);

            WxGoodsCategoryVo wxGoodsCategoryVo = new WxGoodsCategoryVo();
            wxGoodsCategoryVo.setBrotherCategory(brotherCategories);
            wxGoodsCategoryVo.setCurrentCategory(category);
            wxGoodsCategoryVo.setParentCategory(currentCategory);

            return wxGoodsCategoryVo;

        }

        //如果是l2
        //查询兄弟Category
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.createCriteria().andPidEqualTo(currentCategory.getPid()).andLevelEqualTo("L2");
        List<Category> brotherCategories = categoryMapper.selectByExample(categoryExample);

        //查询父Category
        CategoryExample categoryExampleParent = new CategoryExample();
        categoryExampleParent.createCriteria().andIdEqualTo(currentCategory.getPid());
        List<Category> parentCategory = categoryMapper.selectByExample(categoryExampleParent);

        WxGoodsCategoryVo wxGoodsCategoryVo = new WxGoodsCategoryVo();
        wxGoodsCategoryVo.setBrotherCategory(brotherCategories);
        wxGoodsCategoryVo.setCurrentCategory(currentCategory);
        wxGoodsCategoryVo.setParentCategory(parentCategory.get(0));

        return wxGoodsCategoryVo;
    }

    @Override
    public Long goodsCount() {
        GoodsExample goodsExample = new GoodsExample();
        //查询未下架的商品数量
        goodsExample.createCriteria().andDeletedEqualTo(false);
        return goodsMapper.countByExample(goodsExample);
    }

    @Override
    public WxGoodsListVo list(Integer categoryId, Integer page, Integer size, String keyword, String sort, String desc) {

        PageHelper.startPage(page, size);

        GoodsExample goodsExample = new GoodsExample();
//        goodsExample.setOrderByClause("sort_order desc");
        goodsExample.setOrderByClause(sort + " " + desc);
        GoodsExample.Criteria criteria = goodsExample.createCriteria();

        //只查询未删除的商品
        criteria.andDeletedEqualTo(false);
        if (keyword != null) {
            criteria.andNameLike("%" + keyword + "%");//添加传入的keyword模糊搜索
        }else {
            criteria.andCategoryIdEqualTo(categoryId);
        }
        List<Goods> goods = goodsMapper.selectByExample(goodsExample);

        //通过PageInfo获取分页信息
        PageInfo<Goods> goodsPageInfo = new PageInfo<>(goods);
        long count = goodsPageInfo.getTotal();

        //查询分类信息
        CategoryExample categoryExample = new CategoryExample();
        List<Category> categories = categoryMapper.selectByExample(categoryExample);

        WxGoodsListVo wxGoodsListVo = new WxGoodsListVo();
        wxGoodsListVo.setCount(count);
        wxGoodsListVo.setGoodsList(goods);
        wxGoodsListVo.setFilterCategoryList(categories);

        //添加搜索记录
        getIdAndUsername();
        if (keyword != null && id != null & username != null) {
            SearchHistory searchHistory = new SearchHistory();
            searchHistory.setUserId(id);
            searchHistory.setKeyword(keyword);
            Date date = new Date();
            searchHistory.setAddTime(date);
            searchHistory.setUpdateTime(date);
            searchHistory.setFrom(username);
            searchHistoryMapper.insertSelective(searchHistory);
        }

        return wxGoodsListVo;

    }

    @Override
    public WxGoodsDetailVo detail(Integer id) {

        //先拿到商品信息
        Goods goods = goodsMapper.selectByPrimaryKey(id);

        WxGoodsDetailVo wxGoodsDetailVo = new WxGoodsDetailVo();

        //attribute
        wxGoodsDetailVo.setAttribute(getAttribute(id));

        //brand
        wxGoodsDetailVo.setBrand(getBrand(goods.getBrandId()));

        //comment
        wxGoodsDetailVo.setComment(getComment(id));

        //GroupOn
        wxGoodsDetailVo.setGroupon(getGroupon(id));

        //info
        GoodsGalleryList generate = GoodsGalleryList.generate(goods);
        wxGoodsDetailVo.setInfo(generate);

        //issue
        wxGoodsDetailVo.setIssue(getIssue());

        //productList
        wxGoodsDetailVo.setProductList(getProductList(id));

        //shareImg
        wxGoodsDetailVo.setShareImage("");

        //specificationList
        wxGoodsDetailVo.setSpecificationList(getSpecificationList(id));

        //userHasCollect
        wxGoodsDetailVo.setUserHasCollect(0);

        return wxGoodsDetailVo;

    }

    @Override
    public GoodsListVo related(Integer id) {

        //拿该类目下最欢迎的商品

        Goods goods = goodsMapper.selectByPrimaryKey(id);

        Integer categoryId = goods.getCategoryId();

        GoodsExample goodsExample = new GoodsExample();
        goodsExample.setOrderByClause("sort_order desc limit 6");
        goodsExample.createCriteria().andCategoryIdEqualTo(categoryId).andDeletedEqualTo(false);

        List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);

        GoodsListVo goodsListVo = new GoodsListVo();
        goodsListVo.setGoodsList(goodsList);

        return goodsListVo;
    }

    @Autowired
    GoodsSpecificationMapper goodsSpecificationMapper;

    private List<GoodsSpecificationListVo> getSpecificationList(Integer id) {

        GoodsSpecificationExample goodsSpecificationExample = new GoodsSpecificationExample();
        goodsSpecificationExample.createCriteria().andGoodsIdEqualTo(id).andDeletedEqualTo(false);

        //拿到全部的分类
        List<GoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);

        //该分类还需要通过specification进行区分
        TreeSet<String> specification = new TreeSet<>();

        for (GoodsSpecification goodsSpecification : goodsSpecifications) {
            String s = goodsSpecification.getSpecification();
            specification.add(s);
        }


        ArrayList<GoodsSpecificationListVo> goodsSpecificationListVos = new ArrayList<>();
        //取出不同的specification
        for (String s : specification) {

            GoodsSpecificationListVo goodsSpecificationListVo = new GoodsSpecificationListVo();

            GoodsSpecificationExample goodsSpecificationExample2 = new GoodsSpecificationExample();
            goodsSpecificationExample2.createCriteria().andGoodsIdEqualTo(id).andDeletedEqualTo(false).andSpecificationEqualTo(s);
            List<GoodsSpecification> goodsSpecifications2 = goodsSpecificationMapper.selectByExample(goodsSpecificationExample2);

            goodsSpecificationListVo.setName(s);
            goodsSpecificationListVo.setValueList(goodsSpecifications2);

            goodsSpecificationListVos.add(goodsSpecificationListVo);
        }

        return goodsSpecificationListVos;
    }

    @Autowired
    GoodsProductMapper goodsProductMapper;

    private List<GoodsProduct> getProductList(Integer id) {

        GoodsProductExample goodsProductExample = new GoodsProductExample();
        goodsProductExample.createCriteria().andDeletedEqualTo(false).andGoodsIdEqualTo(id);
        return goodsProductMapper.selectByExample(goodsProductExample);
    }

    @Autowired
    IssueMapper issueMapper;

    private List<Issue> getIssue() {

        IssueExample issueExample = new IssueExample();
        issueExample.createCriteria().andDeletedEqualTo(false);
        return issueMapper.selectByExample(issueExample);
    }

    @Autowired
    GrouponRulesMapper grouponRulesMapper;

    private List<GrouponRules> getGroupon(Integer id) {

        GrouponRulesExample grouponRulesExample = new GrouponRulesExample();
        grouponRulesExample.createCriteria().andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        return grouponRulesMapper.selectByExample(grouponRulesExample);

    }

    @Autowired
    CommentMapper commentMapper;

    private DetailCommentVo getComment(Integer id) {

        CommentExample commentExample = new CommentExample();
        commentExample.setOrderByClause("add_time desc limit 5");
        commentExample.createCriteria().andDeletedEqualTo(false).andValueIdEqualTo(id);
        List<Comment> comments = commentMapper.selectByExample(commentExample);

        CommentExample commentExampleCount = new CommentExample();
        commentExampleCount.createCriteria().andDeletedEqualTo(false).andValueIdEqualTo(id);
        long count = commentMapper.countByExample(commentExampleCount);

        DetailCommentVo detailCommentVo = new DetailCommentVo();
        detailCommentVo.setData(comments);
        detailCommentVo.setCount(count);
        return detailCommentVo;
    }

    @Autowired
    BrandMapper brandMapper;

    private Brand getBrand(Integer id) {
        return brandMapper.selectByPrimaryKey(id);
    }

    @Autowired
    GoodsAttributeMapper attributeMapper;

    private List<GoodsAttribute> getAttribute(Integer id) {

        GoodsAttributeExample goodsAttributeExample = new GoodsAttributeExample();
        goodsAttributeExample.createCriteria().andDeletedEqualTo(false).andGoodsIdEqualTo(id);
        return attributeMapper.selectByExample(goodsAttributeExample);
    }

    @Autowired
    UserMapper userMapper;

    private void getIdAndUsername() {
        Subject subject = SecurityUtils.getSubject();
        username = (String) subject.getPrincipal();
        if (username == null)return;
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);
        id = users.get(0).getId();
    }
}
